import hec.heclib.dss.HecDss as HecDss
import Tools 
import Param
import LogUtils
import os
import posixpath as ppath





## Config
#=======================================================



_runFolder = None
_dssFolder = None
_lookupFolder = None

_beginFutureYR = None
_beginPastYR = None
_endPastYR = None
_totalYR = None

_inDssFile = None
_outDssFile = None

_styTemplateFile = None
_tableTemplateList = None

#inDssPath   = 'dss/OriginalSV.dss'
#outDssPath  = 'dss/ShiftedSV.dss'
#
#tableTemplatePath  = 'lookup/wytypes.template'
#studyTemplatePath = 'run/study.template'
#
#logFilePath = 'PA.log'

#outTablePath_prepend = 'lookup/wytypes_'
#outStudyPath_prepend = 'run/study_'
#=======================================================




def setConfig(runFolder, dssFolder, lookupFolder, inDssFile, outDssFile,
              styTemplateFile, tableTemplateList):
    
    global _runFolder
    global _dssFolder
    global _lookupFolder
    global _inDssFile 
    global _outDssFile 
    global _styTemplateFile 
    global _tableTemplateList
    
    _runFolder = runFolder
    _dssFolder = dssFolder
    _lookupFolder = lookupFolder
    _inDssFile = inDssFile
    _outDssFile = outDssFile
    _styTemplateFile = styTemplateFile
    _tableTemplateList = tableTemplateList
    ## Initialize logging
    Param.logger = LogUtils.initLogging(os.path.join(_runFolder,Param.logFile))
   
    

def setTime(beginYR, endYR, totalYR, futureYR):
    
    global _beginFutureYR
    global _beginPastYR
    global _endPastYR
    global _totalYR
     
    _beginFutureYR = futureYR  
    _beginPastYR = beginYR     
    _endPastYR = endYR         
    _totalYR = totalYR         


## Copy historical data ( 5 years sequentially) to future
def cleanDss():
    
    outDssPath  = os.path.join(_dssFolder, _outDssFile)  
    
    try:
        os.remove(outDssPath)
        Param.logger.warning("DSS deleted: "+outDssPath)
    except:    
        pass                               

## Copy historical data ( 5 years sequentially) to future
def processDss():
    
    inDssPath   = ppath.join(_dssFolder, _inDssFile)
    outDssPath  = ppath.join(_dssFolder, _outDssFile)
    
    Tools.cleanDssCatalog(inDssPath)
    
    inFile =  HecDss.open(inDssPath)
    outFile = HecDss.open(outDssPath) 
    
    for pastYR in range( _beginPastYR, _endPastYR + 1 ):
           
        Tools.copyDssToFuture(inFile, outFile, pastYR, _totalYR, _beginFutureYR)
    
    inFile.close()
    outFile.close()

    Param.logger.info("Finished processDss") 
    
## Copy historical water-pastYR types to future
def processTable(tableTemplatePath):
    
    #tableTemplatePath= os.path.normpath(tableTemplatePath)
    #tableTemplatePath = tableTemplatePath.replace("\\","/")
    print tableTemplatePath

    inTable = open(tableTemplatePath,'r') # read only 
    outTablePath_prepend = os.path.splitext(tableTemplatePath)[0]+'_'
    
    for pastYR in range( _beginPastYR, _endPastYR + 1 ):
        
        Fpart = str(pastYR) + '_' + str(pastYR + _totalYR - 1)
    
        outTablePath = outTablePath_prepend + Fpart + '.table_PA'    
        outTable  = open(outTablePath,'w')     
        inTable.seek(0,0) # rewind to beginning of file
            
        Tools.copyWYTypesToFuture(inTable, outTable, pastYR, _totalYR, _beginFutureYR)
        
        outTable.close()
        
    inTable.close()


def cleanTables():
        
    Tools.deleteFile(_lookupFolder, "table_PA")

## Copy historical water-pastYR types to future
def processTables():
        
    for item in _tableTemplateList:
        templatePath = os.path.join(_lookupFolder, item)
        
        processTable(templatePath)
        
    Param.logger.info("Finished processTables")        


def cleanSty():
        
    Tools.deleteFile(_runFolder, "sty_PA")
    

## Generate sty file
def processSty():
    
    styTemplatePath = os.path.join(_runFolder, _styTemplateFile)
    
    for pastYR in range( _beginPastYR, _endPastYR + 1):
        
        Fpart = str(pastYR) + '_' + str(pastYR + _totalYR - 1)
        
        outStudyPath_prepend = styTemplatePath.replace('.template','_')
        outStudyFilePath = outStudyPath_prepend + Fpart + '.sty_PA' 
        
        Tools.generateStudyFile(styTemplatePath, outStudyFilePath, Fpart)

    Param.logger.info("Finished processSty")  

## Generate run batch
def processRunBatch():
    
    runTemplatePath = os.path.join(Param.templateDir, Param.runTemplateFile)
    
    outFileName = Param.runBatchName
    outFilePath = os.path.join(_runFolder, outFileName)
    
    outFile = open(outFilePath,'w')
    
    runTemplate = open(runTemplatePath,'r')
    textTemplate = runTemplate.read()
    
    year_range = ''
    table_list = ''
    
    for pastYR in range( _beginPastYR, _endPastYR + 1):
        
        Fpart = str(pastYR) + '_' + str(pastYR + _totalYR - 1) 
        year_range = year_range + ' ' + Fpart 

    for item in _tableTemplateList:
        
        table_list = table_list + ' ' + os.path.splitext(item)[0] 
       
                
    text=textTemplate.replace('{year_range}', year_range)
    text=text.replace('{table_list}', table_list)
    
    outFile.write(text)
    
    outFile.close()